<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Fast Bridge - 宿主页面示例</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 20px;
        background: #f5f5f5;
      }
      .container {
        max-width: 1200px;
        margin: 0 auto;
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      }
      .iframe-container {
        border: 2px solid #ddd;
        border-radius: 8px;
        margin: 20px 0;
        overflow: hidden;
      }
      iframe {
        width: 100%;
        height: 600px;
        border: none;
      }
      .controls {
        display: flex;
        gap: 10px;
        margin: 20px 0;
        flex-wrap: wrap;
      }
      button {
        padding: 10px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
      }
      .btn-primary {
        background: #007bff;
        color: white;
      }
      .btn-success {
        background: #28a745;
        color: white;
      }
      .btn-warning {
        background: #ffc107;
        color: black;
      }
      .btn-danger {
        background: #dc3545;
        color: white;
      }
      .btn-info {
        background-color: #17a2b8;
        color: white;
      }
      .btn-secondary {
        background-color: #6c757d;
        color: white;
      }
      .status {
        padding: 10px;
        border-radius: 4px;
        margin: 10px 0;
      }
      .status.connected {
        background: #d4edda;
        color: #155724;
      }
      .status.disconnected {
        background: #f8d7da;
        color: #721c24;
      }
      .log {
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 4px;
        padding: 10px;
        height: 200px;
        overflow-y: auto;
        font-family: monospace;
        font-size: 12px;
      }
      .stats {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 10px;
        margin: 10px 0;
      }
      .stat-item {
        background: #e9ecef;
        padding: 10px;
        border-radius: 4px;
        text-align: center;
      }
      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #007bff;
      }
      .stat-label {
        font-size: 12px;
        color: #6c757d;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>🚀 Fast Bridge - 宿主页面</h1>

      <div id="status" class="status disconnected">状态: 正在连接...</div>

      <div class="controls">
        <button id="pingBtn" class="btn-success" disabled>Ping 测试</button>
        <button id="callBtn" class="btn-success" disabled>调用客户端方法</button>
        <button id="emitBtn" class="btn-warning" disabled>发送事件</button>
        <button id="reconnectBtn" class="btn-warning" disabled>重连</button>
        <button id="disconnectBtn" class="btn-danger" disabled>断开连接</button>
      </div>

      <div class="demo-section">
        <h3>⚡ 异步方法测试</h3>
        <div class="controls">
          <button id="fetchUserBtn" class="btn-primary" disabled>调用客户端 fetchData</button>
          <button id="processDataBtn" class="btn-success" disabled>调用客户端 performTask</button>
          <button id="simulateErrorBtn" class="btn-warning" disabled>调用客户端 validateInput</button>
          <button id="batchProcessBtn" class="btn-info" disabled>调用客户端 batchProcessData</button>
        </div>
        <div id="asyncResult" class="result">等待连接...</div>
      </div>

      <div class="stats" id="stats">
        <div class="stat-item">
          <div class="stat-value" id="sentCount">0</div>
          <div class="stat-label">发送消息</div>
        </div>
        <div class="stat-item">
          <div class="stat-value" id="receivedCount">0</div>
          <div class="stat-label">接收消息</div>
        </div>
        <div class="stat-item">
          <div class="stat-value" id="errorCount">0</div>
          <div class="stat-label">错误数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value" id="pingTime">-</div>
          <div class="stat-label">Ping 延迟(ms)</div>
        </div>
      </div>

      <div class="iframe-container">
        <iframe id="clientFrame" src="./client.html"></iframe>
      </div>

      <h3>日志</h3>
      <div id="log" class="log"></div>
    </div>

    <script type="module">
      import { FastBridge } from "../../src/index.js";

      // 获取 DOM 元素
      const statusEl = document.getElementById("status");
      const pingBtn = document.getElementById("pingBtn");
      const callBtn = document.getElementById("callBtn");
      const emitBtn = document.getElementById("emitBtn");
      const reconnectBtn = document.getElementById("reconnectBtn");
      const disconnectBtn = document.getElementById("disconnectBtn");
      const logEl = document.getElementById("log");
      const iframe = document.getElementById("clientFrame");

      // 异步方法测试按钮
      const fetchUserBtn = document.getElementById("fetchUserBtn");
      const processDataBtn = document.getElementById("processDataBtn");
      const simulateErrorBtn = document.getElementById("simulateErrorBtn");
      const batchProcessBtn = document.getElementById("batchProcessBtn");
      const asyncResultEl = document.getElementById("asyncResult");

      // 统计元素
      const sentCountEl = document.getElementById("sentCount");
      const receivedCountEl = document.getElementById("receivedCount");
      const errorCountEl = document.getElementById("errorCount");
      const pingTimeEl = document.getElementById("pingTime");

      // 日志函数
      function log(message, type = "info") {
        const time = new Date().toLocaleTimeString();
        const logEntry = document.createElement("div");
        logEntry.style.color = type === "error" ? "red" : type === "warn" ? "orange" : "black";
        logEntry.textContent = `[${time}] ${message}`;
        logEl.appendChild(logEntry);
        logEl.scrollTop = logEl.scrollHeight;
      }

      // 创建 FastBridge 实例
      const bridge = new FastBridge({
        namespace: "demo",
        debug: true,
        iframe: iframe,
      });

      // 注册方法供客户端调用
      bridge.register("getHostInfo", async (params) => {
        log(`客户端请求宿主信息: ${JSON.stringify(params)}`);
        return {
          title: "Fast Bridge 宿主页面",
          timestamp: Date.now(),
          userAgent: navigator.userAgent,
          ...params,
        };
      });

      bridge.register("calculate", async (params) => {
        const { a, b, operation } = params;
        log(`客户端请求计算: ${a} ${operation} ${b}`);

        let result;
        switch (operation) {
          case "+":
            result = a + b;
            break;
          case "-":
            result = a - b;
            break;
          case "*":
            result = a * b;
            break;
          case "/":
            result = a / b;
            break;
          default:
            throw new Error(`不支持的操作: ${operation}`);
        }

        return { result, operation, a, b };
      });

      // 添加异步方法示例
      bridge.register("fetchUserData", async (params) => {
        const { userId } = params;
        log(`客户端请求用户数据: userId=${userId}`);

        // 模拟异步网络请求
        await new Promise((resolve) => setTimeout(resolve, 1000));

        // 模拟从数据库获取数据
        const userData = {
          id: userId,
          name: `用户${userId}`,
          email: `user${userId}@example.com`,
          avatar: `https://api.example.com/avatars/${userId}.jpg`,
          lastLogin: new Date().toISOString(),
          status: "active",
        };

        log(`返回用户数据: ${JSON.stringify(userData)}`);
        return userData;
      });

      bridge.register("processData", async (params) => {
        const { data, operation } = params;
        log(`客户端请求数据处理: operation=${operation}, data=${JSON.stringify(data)}`);

        // 模拟复杂的数据处理
        await new Promise((resolve) => setTimeout(resolve, 800));

        let processedData;
        switch (operation) {
          case "sort":
            processedData = [...data].sort((a, b) => a - b);
            break;
          case "filter":
            processedData = data.filter((item) => item > 0);
            break;
          case "map":
            processedData = data.map((item) => item * 2);
            break;
          case "reduce":
            processedData = data.reduce((sum, item) => sum + item, 0);
            break;
          default:
            throw new Error(`不支持的操作: ${operation}`);
        }

        log(`数据处理完成: ${JSON.stringify(processedData)}`);
        return {
          original: data,
          processed: processedData,
          operation,
          timestamp: Date.now(),
        };
      });

      bridge.register("simulateError", async (params) => {
        const { errorType } = params;
        log(`客户端请求模拟错误: ${errorType}`);

        // 模拟异步操作
        await new Promise((resolve) => setTimeout(resolve, 500));

        // 根据错误类型抛出不同的错误
        switch (errorType) {
          case "network":
            throw new Error("网络连接失败");
          case "permission":
            throw new Error("权限不足");
          case "validation":
            throw new Error("数据验证失败");
          case "timeout":
            throw new Error("请求超时");
          default:
            throw new Error("未知错误");
        }
      });

      bridge.register("simulateLongOperation", async (params) => {
        const { operation, steps = 3 } = params;
        log(`客户端请求长时间操作: ${operation}, 步骤数: ${steps}`);

        const results = [];

        for (let i = 1; i <= steps; i++) {
          // 模拟每个步骤的执行
          await new Promise((resolve) => setTimeout(resolve, 800));

          const stepResult = {
            step: i,
            status: "completed",
            message: `步骤 ${i} 完成`,
            progress: (i / steps) * 100,
          };

          results.push(stepResult);
          log(`步骤 ${i} 完成: ${JSON.stringify(stepResult)}`);
        }

        const finalResult = {
          operation,
          totalSteps: steps,
          results,
          completed: true,
          timestamp: Date.now(),
        };

        log(`长时间操作完成: ${JSON.stringify(finalResult)}`);
        return finalResult;
      });

      bridge.register("streamData", async (params) => {
        const { count = 30, interval = 200 } = params;
        log(`客户端请求流式数据: 数量=${count}, 间隔=${interval}ms`);

        const dataStream = [];
        const startTime = Date.now();

        for (let i = 1; i <= count; i++) {
          // 模拟数据生成间隔
          await new Promise((resolve) => setTimeout(resolve, interval));

          const dataItem = {
            id: i,
            type: ["user", "product", "order", "log"][Math.floor(Math.random() * 4)],
            content: `流式数据_${i}`,
            timestamp: Date.now(),
            metadata: {
              source: "host",
              priority: Math.floor(Math.random() * 5) + 1,
              tags: ["stream", "real-time", `batch-${Math.floor(i / 10)}`],
            },
          };

          dataStream.push(dataItem);

          // 每5条数据记录一次进度
          if (i % 5 === 0) {
            log(`流式数据生成进度: ${i}/${count} (${Math.round((i / count) * 100)}%)`);
          }
        }

        const endTime = Date.now();
        const totalTime = endTime - startTime;

        const finalResult = {
          totalItems: count,
          generatedItems: dataStream.length,
          totalTime,
          averageInterval: totalTime / count,
          dataStream,
          completed: true,
          timestamp: endTime,
        };

        log(`流式数据生成完成: 生成了 ${count} 条数据，总耗时 ${totalTime}ms`);
        return finalResult;
      });

      // 监听客户端事件
      bridge.on("clientReady", (data) => {
        log(`客户端准备就绪: ${JSON.stringify(data)}`, "success");
      });

      bridge.on("clientError", (data) => {
        log(`客户端错误: ${JSON.stringify(data)}`, "error");
      });

      bridge.on("userAction", (data) => {
        log(`用户操作: ${JSON.stringify(data)}`);
      });

      // 监听连接状态变化
      bridge.onConnectionChange((connected) => {
        statusEl.textContent = `状态: ${connected ? "已连接" : "未连接"}`;
        statusEl.className = `status ${connected ? "connected" : "disconnected"}`;

        // 更新按钮状态
        const connectedButtons = [
          pingBtn,
          callBtn,
          emitBtn,
          reconnectBtn,
          disconnectBtn,
          fetchUserBtn,
          processDataBtn,
          simulateErrorBtn,
          batchProcessBtn,
        ];
        connectedButtons.forEach((btn) => (btn.disabled = !connected));

        log(`连接状态变化: ${connected ? "已连接" : "未连接"}`);
      });

      // 更新统计信息
      function updateStats() {
        const stats = bridge.getMessageStats();
        sentCountEl.textContent = stats.sent;
        receivedCountEl.textContent = stats.received;
        errorCountEl.textContent = stats.errors;
      }

      // 定期更新统计
      setInterval(updateStats, 1000);

      // 事件处理
      pingBtn.addEventListener("click", async () => {
        try {
          const latency = await bridge.ping();
          pingTimeEl.textContent = latency;
          log(`Ping 成功，延迟: ${latency}ms`, "success");
        } catch (error) {
          log(`Ping 失败: ${error.message}`, "error");
        }
      });

      callBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("getClientInfo", {
            includeStats: true,
            timestamp: Date.now(),
          });
          log(`调用客户端方法成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          log(`调用客户端方法失败: ${error.message}`, "error");
        }
      });

      emitBtn.addEventListener("click", () => {
        const eventData = {
          message: "来自宿主的问候",
          timestamp: Date.now(),
          random: Math.random(),
        };
        bridge.emit("hostMessage", eventData);
        log(`发送事件到客户端: ${JSON.stringify(eventData)}`);
      });

      reconnectBtn.addEventListener("click", async () => {
        try {
          log("开始重连...");
          await bridge.reconnect();
          log("重连成功", "success");
        } catch (error) {
          log(`重连失败: ${error.message}`, "error");
        }
      });

      disconnectBtn.addEventListener("click", () => {
        bridge.disconnect();
        log("连接已断开");
      });

      // 异步方法测试
      fetchUserBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("fetchData", {
            type: "user",
            id: Math.floor(Math.random() * 100) + 1,
          });
          asyncResultEl.textContent = JSON.stringify(result, null, 2);
          log(`异步方法调用成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          asyncResultEl.textContent = `错误: ${error.message}`;
          log(`异步方法调用失败: ${error.message}`, "error");
        }
      });

      processDataBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("performTask", {
            task: "数据处理",
            duration: 1500,
          });
          asyncResultEl.textContent = JSON.stringify(result, null, 2);
          log(`异步方法调用成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          asyncResultEl.textContent = `错误: ${error.message}`;
          log(`异步方法调用失败: ${error.message}`, "error");
        }
      });

      simulateErrorBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("validateInput", {
            data: "invalid-email",
            rules: ["required", "email"],
          });
          asyncResultEl.textContent = JSON.stringify(result, null, 2);
          log(`异步方法调用成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          asyncResultEl.textContent = `错误: ${error.message}`;
          log(`异步方法调用失败: ${error.message}`, "error");
        }
      });

      batchProcessBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("batchProcessData", {
            count: 100, // 例如处理100条数据
            delay: 50, // 每条数据处理延迟50ms
          });
          asyncResultEl.textContent = JSON.stringify(result, null, 2);
          log(`批量处理方法调用成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          asyncResultEl.textContent = `错误: ${error.message}`;
          log(`批量处理方法调用失败: ${error.message}`, "error");
        }
      });

      // 页面加载完成后自动初始化
      window.addEventListener("load", async () => {
        log("页面加载完成，准备初始化连接...");
        try {
          const startTime = Date.now();
          await bridge.init();
          const endTime = Date.now();
          log(`连接初始化成功，耗时: ${endTime - startTime}ms`, "success");
        } catch (error) {
          log(`连接初始化失败: ${error.message}`, "error");
        }
      });
    </script>
  </body>
</html>
